import mx.utils.Delegate;
/**
 * @author pbalogh
 */
class Main 
{

	private var _stage : MovieClip;

	private var _terminii : Array;
	
	private var _springs : Array;
	
	public static function mainfunc( stage:MovieClip ):Void
	{
		// we need to instantiate a single Main object
		// so we can call its methods via Delegate and such.
		var m : Main = new Main( stage );
	}
	
	public function Main ( stage : MovieClip )
	{
		_stage = stage;
		
		var NUMBER_OF_TERMINII:Number = 10;
		
		// let's create our endpoint objects
		// as Terminus objects ( simple wrappers for movie clips)
		// and keep them in an array
		
		_terminii = new Array(); 
		
		
		for( var i:Number = 0; i < NUMBER_OF_TERMINII; i++ )
		{
			var mc:MovieClip = 	_stage.createEmptyMovieClip("mc" + i, _stage.getNextHighestDepth() );
			mc.beginFill( Math.random() * 0xffffff, 100 );
			mc.moveTo( -10, -10 );
			mc.lineTo( 10, -10 );
			mc.lineTo( 10, 10 );
			mc.lineTo( -10, 10 );
			mc.lineTo ( -10, -10 );
			mc.endFill();
			mc._x = Math.random() * 400;
			mc._y = Math.random() * 400;
			var randomMass:Number = 10 + Math.random() * 30;
			var term:Terminus = new Terminus( mc, randomMass );
			_terminii.push( term );
		}
		
		// now let's create our springs
		// giving each one a pair of endpoints (terminii ) 
		// and a random strength factor.
		
		_springs = new Array(); 
		
		for( var i:Number = 0; i < NUMBER_OF_TERMINII; i++ )
		{
			var startpoint:Terminus = _terminii [ i ];
			var endpoint:Terminus = null;
			if( i == NUMBER_OF_TERMINII - 1 ) // we're at the end of our terminii, so wrap around
			{
				endpoint = _terminii[ 0 ];
			}
			else
			{
				endpoint = _terminii[ i + 1 ];
			}
			
			if( endpoint != null)
			{
				var spring:Spring = new Spring( startpoint, endpoint, .1 + Math.random() * .05 );
				
				_springs.push( spring );
			}
		}
		
		
		
		// so now we've got an array of terminii 
		// and an array of springs.
		
		_stage.onEnterFrame = Delegate.create( this, onEnterFrameHandler );
	}
	
	public function onEnterFrameHandler() : Void
	{
		
		// first we cycle through all springs to impart forces to all terminii,
		// and then we cycle through all terminii to make them react.
		_stage.clear();
		_stage.lineStyle( 1, 0, 100 );
		for( var i:Number = 0; i < _springs.length; i++ )
		{
			_springs[ i ].onEnterFrameHandler();
			_stage.moveTo( _springs[ i ]._sp._x, _springs[ i ]._sp._y );
			_stage.lineTo( _springs[ i ]._ep._x, _springs[ i ]._ep._y );
		}
		
		for( var i:Number = 0; i < _terminii.length; i++ )
		{
			_terminii[ i ].onEnterFrameHandler();
		}
		
	}
}